package com.xinzhi.savingpot.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xinzhi.savingpot.rminfo.service.impl.LimitAllImpl;
import com.xinzhi.savingpot.rminfo.service.impl.RecordinfoAllImpl;
import com.xinzhi.savingpot.userinfo.entity.UserInfo;
import com.xinzhi.savingpot.userinfo.service.impl.LoginServiceImpl;
import com.xinzhi.savingpot.util.JwtUtils;
import com.xinzhi.savingpot.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginServiceImpl loginService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    RecordinfoAllImpl recordinfoAll;
    @Autowired
    LimitAllImpl limitAll;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //执行认证
        if (token == null) {
            throw new RuntimeException("尚未登陆!");
        }
        //获取token中的主体部分
        String userid;
        try {
            //从解密的token中获取主体部分
            userid = JWT.decode(token).getAudience().get(0);

        } catch (JWTDecodeException j) {
            throw new JWTDecodeException("token异常!请重新登陆");
        }


        //拿userid进入数据库中判断库中是否有此用户
        UserInfo user = loginService.findUserById(Integer.parseInt(userid));

        if (user == null) {
            throw new RuntimeException("未找到该用户!");
        }
        String token1 = (String) redisUtil.get("Token:" + userid);


        // 验证 token私钥部分是否与用户的密码一致.
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            if (token.equals(token1)){
                return true;
            }else {
                jwtVerifier.verify(token);
                UserInfo dbuser = (UserInfo) redisUtil.get("User");
                if (dbuser != null){
                    String token2 = JwtUtils.createJsonWebToken(user);
                    redisUtil.set("Token:" , token2,60*60*1000);
                }
            }
        } catch (JWTVerificationException e) {
            throw new RuntimeException("token异常!请重新登陆");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
